<?php

/**
 * Class WeiboManager
 */
class WeiboManger
{
    public static function checkWeiboBind()
    {
    	/** @var $CI CI */
        $CI =& get_instance();

    	//weibo get user_key
    	$token = $CI->session->userdata('token');
        $userID=$CI->session->userdata('UserID');
        $o  = new SaeTClientV2(WB_AKEY , WB_SKEY,$token['access_token']);
        $uid_get = $o->get_uid();
        if(isset($uid_get['error_code']) && $uid_get['error_code']==='20301')
        {
            return 'fail';
            exit;
        }else{
            $uid = $uid_get['uid'];
            $weiboInfo=WeiboInfo_Model::getByWeiboId($uid);
            if($weiboInfo !==null && !$userID)
            {
                $userid = $weiboInfo->getUserId();
                $userinfo = User_Model::getUserById($userid);
                //检查是否获取成功
                if (!$userinfo || $userinfo->getID() == 0)
                    throw new NotExistException('UserID不存在');

                $thatUser = UserManager::login($userinfo->getEmail(), $userinfo->getPassword(),'1');
                return 'login';
            }elseif($weiboInfo !==null && $userID!== '')
            {
                return 'noAllow';
            }else{
                return 'noBind';
            }
        }
    }

    public static function getWeiboInfo()
    {
        /** @var $CI CI */
        $CI =& get_instance();
//        try
//        {
            $token = $CI->session->userdata('token');
            $o  = new SaeTClientV2(WB_AKEY , WB_SKEY,$token['access_token']);
            $uid_get = $o->get_uid();
            $uid = $uid_get['uid'];
            $user_message = $o->show_user_by_id( $uid);
            $userWeiboInfo = array(
                'name'           => $user_message['name'],
                'token'          => $token['access_token'],
                'weibo_id'       => $uid,
                'photos'         => $user_message['avatar_large'],
                'gender'         => $user_message['gender'],
                'description'    => $user_message['description'],
                'data_json'      => $user_message,
                'location'       => $user_message['location'],
            );
          //  $o->update('我在yime网上有新帐号咯，朋友们也加入吧，测试测试→http://www.hiyime.com');
            return $userWeiboInfo;
//        }catch (ErrorException e)
//        {
//
//        }
    }

    public static function addWeiboInfo()
    {
        /** @var $CI CI */
        $CI =& get_instance();
        $CI->load->library('Weibo');
        $userInfo=UserManager::getCurrentUserBySession();
        $userWeiboInfo=self::getWeiboInfo();
        if($userWeiboInfo){
            $thatWeiboInfo= new Weibo();
            $thatWeiboInfo->setUserId($userInfo->getId());
            $thatWeiboInfo->setName($userWeiboInfo['name']);
            $thatWeiboInfo->setToken($userWeiboInfo['token']);
            $thatWeiboInfo->setWeiboId($userWeiboInfo['weibo_id']);
            $thatWeiboInfo->setPhotos($userWeiboInfo['photos']);
            $thatWeiboInfo->setGender($userWeiboInfo['gender']);
            $thatWeiboInfo->setDescription($userWeiboInfo['description']);
            $thatWeiboInfo->setLocation($userWeiboInfo['location']);
            $result=WeiboInfo_Model::add($thatWeiboInfo);
            if(!$result)
            {
                return $result;
            }else
            {
                return false;
            }
        }else{
            return false;
        }

    }

    public static  function setWeiboInfoToUserInfo()
    {
        /** @var $CI CI */
        $CI =& get_instance();

        $UserID=$CI->session->userdata('UserID');
        $thatUser=User_Model::getUserById($UserID);
        //检查是否获取成功
        if (!$thatUser || $thatUser->getID() == 0)
            throw new NotExistException('UserID不存在');

        $thatWeiboInfo=self::getWeiboInfo();
        $thatUserInfo = $thatUser->getUserInfo();
        $thatUser->setNickname($thatWeiboInfo['name']);
        User_Model::update($thatUser);
        $weibo_sex=$thatWeiboInfo['gender'];
        //微博性别返回值为m:男性  f:女性   n:未知
        if($weibo_sex === 'm'){
            $sex=1;
        }elseif($weibo_sex === 'f'){
            $sex=2;
        }else{
            $sex=0;
        }

        //截取地区
        $location=explode(' ',$thatWeiboInfo['location']);
        $thatUserInfo->setUserId($UserID);
        $thatUserInfo->setSex($sex);
        $thatUserInfo->setProfile($thatWeiboInfo['description']);
        $thatUserInfo->setProv($location[0]);
        $thatUserInfo->setDist($location[1]);
        $thatUserInfoModel=UserInfo_Model::getUserInfoByUserId($UserID);

        if(!$thatUserInfoModel || $thatUserInfoModel->getId()== 0)
        {
            if ($thatUser->getUserInfoId()) {
                $thatUserInfo = UserInfo_Model::update($thatUserInfo);
            } else {
                $thatUserInfo = UserInfo_Model::add($thatUserInfo);
                $thatUser->setUserInfoId($thatUserInfo->getId());
                User_Model::update($thatUser);
            }
            return true;
        }else{
            return false;
        }
    }

    public static function bindWeibo()
    {
        /** @var $CI CI */
        $CI =& get_instance();
        $addResult = self::addWeiboInfo();
        $setResult = self::setWeiboInfoToUserInfo();
        $CI->session->unset_userdata('bindType');
        if(!$addResult){
            return 'addWeiboInfo_fail';
        }else{
            if(!$setResult){
                return 'setWeiboInfo_fail';
            }else{
                return true;
            }
        }
    }

    /**
     * @param $id
     * @param $type 1 商品  2 求购
     */
    public static function shareByWeibo($id,$type)
    {
        /** @var $CI CI */
        $CI =& get_instance();

        $token = $CI->session->userdata('token');
        $o  = new SaeTClientV2(WB_AKEY , WB_SKEY,$token['access_token']);
        if($type==1){
            $commodity=Commodity_Model::getCommodityById($id);
            $ret=$o->update($commodity->getIntro());
            $ret=$o->upload($commodity->getDisplayImageUrl(),'23');
        }else if($type==2){
            $commodityRequire=CommodityRequire_Model::getCommodityRequireById($id);
            $ret=$o->update($commodityRequire->getTitle());
        }

        if ( isset($ret['error_code']) && $ret['error_code'] > 0 ) {
            echo "<p>发送失败，错误：{$ret['error_code']}:{$ret['error']}</p>";
        } else {
            echo "<p>发送成功</p>";
        }
    }
}